<template>
  <div class="main">
    <div class="title">
      <div>用户管理员</div>
      <el-button type="primary" :icon="CirclePlus" @click="addUser"
        >新增用户</el-button
      >
    </div>
    <div class="search-bar">
      <div class="label-input">
        <span>搜索内容：</span>
        <el-input v-model="query.queryName" style="width: 200px" />
      </div>
      <el-button class="search-btn" @click="getTabelData">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>
    <div class="cut-line"></div>
    <el-table
      :data="tabelData"
      height="400"
      style="width: 100%"
      border
      v-loading="loading"
      :header-cell-style="headerStyle"
    >
      <el-table-column type="index" align="center" label="#" width="50" />
      <el-table-column
        prop="username"
        align="center"
        label="管理员账号"
        width="150"
      />
      <el-table-column prop="role" align="center" label="角色" width="120">
      </el-table-column>
      <el-table-column
        prop="areaName"
        align="center"
        label="区域名称"
        width="150"
      >
      </el-table-column>
      <el-table-column prop="phone" align="center" label="手机号" width="130">
      </el-table-column>
      <el-table-column
        prop="personName"
        align="center"
        label="绑定人姓名"
        width="120"
      >
      </el-table-column>
      <el-table-column
        prop="personId"
        align="center"
        label="绑定人卡号"
        width="150"
      >
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        fixed="right"
        min-width="400"
      >
        <template v-slot="scope">
          <div class="table-buts">
            <el-button
              v-if="scope.row.personId"
              type="danger"
              @click="unBindingUser(scope.row)"
              >解绑读者账号</el-button
            >
            <el-button
              v-else
              style="background-color: #3d839c; color: #fff"
              @click="bindingUser(scope.row)"
              >绑定读者账号</el-button
            >
            <el-button
              style="background-color: #3d839c; color: #fff"
              @click="updateUser(scope.row)"
              >修改</el-button
            >
            <el-button
              style="background-color: #3d839c; color: #fff"
              @click="updateUserPwd(scope.row.id)"
              >修改密码</el-button
            >
            <el-button type="danger" @click="deleteUser(scope.row.id)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="tabelDataTotal"
        :page-size="query.pageSize"
        :current-page="query.pageNum"
        @update:current-page="currentPageChange"
      />
    </div>
    <!-- 添加、修改弹窗 -->
    <el-dialog v-model="dialogTableVisible" :title="title" width="300">
      <div class="dialog-win">
        <el-form
          ref="ruleFormRef"
          :model="table"
          label-width="auto"
          :rules="rules"
        >
          <el-form-item label="用户账号：" prop="username">
            <el-input v-model="table.username" style="width: 240px" />
          </el-form-item>
          <el-form-item
            v-if="title == '添加图书管理员'"
            label="用户密码："
            prop="password"
          >
            <el-input v-model="table.password" style="width: 240px" />
          </el-form-item>
          <el-form-item label="手机号：" prop="phone">
            <el-input v-model="table.phone" style="width: 240px" />
          </el-form-item>
          <el-form-item label="角色：" prop="role">
            <el-select
              v-model="table.role"
              placeholder="请选择角色"
              style="width: 200px"
            >
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.configLabel"
                :value="item.configValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="区域：" prop="areaId" v-if="table.role == '3'">
            <el-select
              v-model="table.areaId"
              placeholder="请选择区域"
              style="width: 200px"
            >
              <el-option
                v-for="item in areaList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <div class="from-but">
              <el-button type="warning" @click="submit(ruleFormRef)"
                >确定</el-button
              >
              <el-button type="info" @click="resetForm(ruleFormRef)"
                >取消</el-button
              >
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!-- 修改密码 -->
    <el-dialog v-model="dialogTablePwdVisible" :title="title" width="300">
      <div class="dialog-win">
        <el-form
          ref="ruleFormPwdRef"
          :model="table"
          label-width="auto"
          :rules="passwordRules"
        >
          <el-form-item label="旧密码：" prop="oldPwd">
            <el-input v-model="table.oldPwd" style="width: 240px" />
          </el-form-item>
          <el-form-item label="新密码：" prop="newPwd">
            <el-input v-model="table.newPwd" style="width: 240px" />
          </el-form-item>
          <el-form-item>
            <div class="from-but">
              <el-button type="warning" @click="submit(ruleFormPwdRef)"
                >确定</el-button
              >
              <el-button type="info" @click="resetForm(ruleFormPwdRef)"
                >取消</el-button
              >
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!-- 绑定读者 -->
    <el-dialog v-model="dialogTableUserVisible" :title="title" width="300">
      <div class="dialog-win">
        <el-form :model="table" label-width="auto">
          <el-form-item label="读者ID" prop="personId">
            <el-input v-model="table.personId" style="width: 240px" />
          </el-form-item>
          <el-form-item>
            <div class="from-but">
              <el-button type="warning" @click="bindingPersonWin"
                >确定</el-button
              >
              <el-button type="info" @click="dialogTableUserVisible = false"
                >取消</el-button
              >
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { CirclePlus } from "@element-plus/icons-vue";
import message from "@/util/alert.js";
import { ref, reactive, onMounted } from "vue";
import { checkMobile } from "@/util/formRules.js";
import { getConfigDefaultApi, getConfigDataApi } from "@/api/configApi.js";
import { getAllAreaListApi } from "@/api/areaApi.js";
import {
  getUserListApi,
  updateUserApi,
  addUserApi,
  deleteUserApi,
  updatePwdApi,
  bindingPersonApi,
  unBindingPerson,
} from "@/api/userApi.js";
import { useConfigStore } from "@/stores";
const configStore = useConfigStore();
// 查询参数
const query = reactive({
  queryName: "",
  pageNum: 1,
  pageSize: 10,
});
const tabelDataTotal = ref(0);
const loading = ref(false);
const tabelData = ref([]);
const roleList = ref([]); //角色列表
const areaList = ref([]); //区域列表
// 表格头部样式
const headerStyle = () => {
  return {
    backgroundColor: "#a0cfff",
    color: "#000000",
    padding: "8px 0px",
  };
};
// 当前页改变
const currentPageChange = (num) => {
  query.pageNum = num;
  getTabelData();
};

// 获取用户列表
const getTabelData = async () => {
  loading.value = true;
  let res = await getUserListApi(query);
  tabelDataTotal.value = res.data.total;
  tabelData.value = res.data.rows;
  loading.value = false;
};

// 删除
const deleteUser = (id) => {
  message.confirm({
    title: "提示",
    msg: `是否删除该用户管理员`,
    ok: async () => {
      await deleteUserApi(id);
      message.success(`删除成功`);
      getTabelData();
    },
  });
};
const dialogTableUserVisible = ref(false);
// 绑定借阅人
const bindingUser = (row) => {
  title.value = "绑定借阅人";
  table.value = {
    personId: "",
    userId: row.id,
  };
  dialogTableUserVisible.value = true;
};
// 确认绑定借阅人
const bindingPersonWin = async () => {
  await bindingPersonApi(table.value.userId, table.value.personId);
  dialogTableUserVisible.value = false;
  getTabelData();
  message.success(`绑定成功`);
};
// 解绑借阅人
const unBindingUser = async (row) => {
  message.confirm({
    title: "提示",
    msg: `是否解绑该图书管理员`,
    ok: async () => {
      await unBindingPerson(row.id, row.personId);
      message.success(`解绑成功`);
      getTabelData();
    },
  });
};
// 修改密码
const updateUserPwd = (id) => {
  title.value = "修改管理员密码";
  table.value = {
    id,
    newPwd: "",
    oldPwd: "",
  };
  dialogTablePwdVisible.value = true;
};
// 重置
const reset = () => {
  Object.assign(query, {
    queryName: "",
    pageNum: 1,
    pageSize: 10,
  });
  getTabelData();
};
// 弹窗
const title = ref("");
const dialogTableVisible = ref(false);
const dialogTablePwdVisible = ref(false);
const ruleFormRef = ref(null);
const ruleFormPwdRef = ref(null);
const table = ref({});

// 添加、修改的规则
const rules = reactive({
  username: [
    { required: true, message: "请输入用户账号", trigger: "blur" },
    { min: 2, max: 8, message: "用户账号长度为2-8", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入用户密码", trigger: "blur" },
    { min: 2, max: 8, message: "密码长度为6-12", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { validator: checkMobile, trigger: "blur" },
  ],
  role: [{ required: true, message: "请分配角色", trigger: "change" }],
  areaId: [{ required: true, message: "请选择区域", trigger: "change" }],
});

// 修改密码的规则
const passwordRules = reactive({
  newPwd: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 2, max: 8, message: "密码长度为6-12", trigger: "blur" },
  ],
  oldPwd: [
    { required: true, message: "请输入旧密码", trigger: "blur" },
    { min: 2, max: 8, message: "密码长度为6-12", trigger: "blur" },
  ],
});
let passwordDefault = "";
// 获取配置信息
const getConfig = async () => {
  // 读取区域列表
  if (!configStore.areaList) {
    let res = await getAllAreaListApi();
    areaList.value = res.data;
    configStore.areaList = res.data;
  }
  areaList.value = configStore.areaList;
  // 读取角色列表
  if (!configStore.roleList) {
    let res = await getConfigDataApi({
      configKey: "system:role:type",
    });
    configStore.roleList = res.data.filter((el) => {
      return el.configLabel !== "系统管理员";
    });
  }
  roleList.value = configStore.roleList;
};
// 添加用户
const addUser = async () => {
  await getConfig();
  if (passwordDefault === "") {
    // 获取默认密码
    let res = await getConfigDefaultApi({
      key: "system:password:default",
    });
    passwordDefault = res.data;
  }
  dialogTableVisible.value = true;
  title.value = "添加用户管理员";
  table.value = {
    password: passwordDefault,
    username: "",
    phone: "",
    areaId: "",
    role: "",
  };
  console.log(roleList.value);
};
// 修改用户信息
const updateUser = async (row) => {
  await getConfig();
  dialogTableVisible.value = true;
  title.value = "修改管理员信息";
  table.value = JSON.parse(JSON.stringify(row));
  console.log(table.value.role);
};
// 提交表单
const submit = async (ruleForm) => {
  if (!ruleForm) return;
  await ruleForm.validate(async (valid, fields) => {
    if (valid) {
      if (title.value == "添加用户管理员") {
        await addUserApi(table.value);
        getTabelData();
        dialogTableVisible.value = false;
        message.success("添加用户管理员成功");
      } else if (title.value == "修改管理员信息") {
        await updateUserApi(table.value);
        getTabelData();
        dialogTableVisible.value = false;
        message.success("修改管理员信息成功");
      } else if (title.value == "修改管理员密码") {
        await updatePwdApi(table.value);
        dialogTablePwdVisible.value = false;
        message.success("修改用户密码成功");
      }
    }
  });
};
// 重置表单
const resetForm = (ruleForm) => {
  ruleForm.resetFields();
  dialogTableVisible.value = false;
  dialogTablePwdVisible.value = false;
  table.value = {};
};
onMounted(() => {
  getTabelData();
});
</script>
        <style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  padding: 10px 20px;
  .title {
    font-size: 20px;
    font-weight: 600;
    display: flex;
    justify-content: space-between;
  }
}
.search-bar {
  margin-top: 20px;
  display: flex;
  align-items: center;
  height: 30px;
  .search-btn {
    background-color: #79bbff;
    color: #ffffff;
  }
  .el-button {
    height: 28px;
  }
}
.label-input {
  display: flex;
  color: #aaaaaa;
  height: 30px;
  align-items: center;
  margin-right: 20px;
  font-weight: 550;
  .el-input {
    border: none;
    height: 30px;
  }
}
.cut-line {
  margin-top: 30px;
  height: 1px;
  background-color: #cdd0d6;
}

.pagination {
  display: flex;
  justify-content: center;

  .el-pagination {
    margin: auto 0;
    margin-top: 10px;
  }
}
:deep(.el-table) {
  margin-top: 20px;
  .el-table__cell {
    padding: 4px;
  }
  .cell {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>